﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Common;
using System.Data;
using System.Globalization;
using System.Text;
using ResourceBlender.DAL;
using ResourceBlender.Core;

public partial class CreateVariant : LocalPage
{
    /// <summary>
    /// Initializes the base and destination language listboxes.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack) {
            litAddAppLink.Text = ASPNETUtils.FormatLink(I18nUtils.GetString("UIStrings", "AddAppLink"), ResolveUrl("~/Applications.aspx"));
            IEnumerable<KeyValuePair<string, CultureInfo>> langs = ResourceBlenderDAL.GetUniqueLanguages();
            foreach(var lang in langs) {
                lstBaseLanguage.Items.Add(new ListItem(lang.Value.EnglishName, lang.Key));
            }

            CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);
            List<ListItem> availableCultures = new List<ListItem>();
            foreach(CultureInfo culture in cultures) {
                if(culture.Name.Length > 0) {
                    ListItem itm = new ListItem(culture.EnglishName, culture.Name);
                    availableCultures.Add(new ListItem(culture.EnglishName, culture.Name));
                }
            }
            availableCultures.Sort(new ListComparer());
            foreach(ListItem itm in availableCultures) {
                lstDestinationLanguage.Items.Add(itm);
            }
            if(langs.Any()) {
                mltMain.ActiveViewIndex = 1;
                lstBaseLanguage.SelectedIndex = 0;
            } else {
                mltMain.ActiveViewIndex = 0;
            }
        }
        pnlError.Visible = false;
        pnlSuccess.Visible = false;
    }

    /// <summary>
    /// Checks a source and destinanation language have been selected and they are different
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs"/> instance containing the event data.</param>
    protected void vldLanguages_ServerValidate(object sender, ServerValidateEventArgs e) {
        if(lstBaseLanguage.SelectedItem == null) {
            vldLanguages.ErrorMessage = I18nUtils.GetString("Errors", "SourceLanguageRequired");
            e.IsValid = false;
        } else if(lstDestinationLanguage.SelectedItem == null) {
            vldLanguages.ErrorMessage = I18nUtils.GetString("Errors", "DestinationLanguageRequired");
            e.IsValid = false;
        } else if(lstBaseLanguage.SelectedItem.Value == lstDestinationLanguage.SelectedItem.Value) {
            vldLanguages.ErrorMessage = I18nUtils.GetString("Errors", "DifferentSourceDestinationLangsRequired");
            e.IsValid = false;
        }
    }

    /// <summary>
    /// Starts copying
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btnCopyTranslations_Click(object sender, EventArgs e) {
        if(!Page.IsValid) {
            return;
        }
        BulletedList lstErrors = new BulletedList(),
                     lstSuccess = new BulletedList();
        try {
            string baseLang = lstBaseLanguage.SelectedItem.Value,
                   destinationLang = lstDestinationLanguage.SelectedItem.Value;
            bool overwrite = radIfExists.SelectedValue == "overwrite";
            int numCopied = 0;
            StatusMessage.StatusChangedEventHandler logHandler = new StatusMessage.StatusChangedEventHandler(message => {
                switch(message.MessageType) {
                    case StatusMessage.StatusMessageType.Error:
                        lstErrors.Items.Add(message.Message);
                        break;
                    default:
                        lstSuccess.Items.Add(message.Message);
                        numCopied++;
                        break;
                }
            });
            ResourceBlenderDAL.CreateVariant(baseLang, destinationLang, overwrite, null, logHandler);
/*
            cmd.AddParameterWithValue("@lang", lstBaseLanguage.SelectedItem.Value);

            
            cmd.Parameters["@lang"].Value = lstDestinationLanguage.SelectedItem.Value;

            int numCopied = 0;
            if(radIfExists.SelectedValue == "leave") {

                try {
                    cmd.ExecuteNonQuery();
                    lstSuccess.Items.Add(string.Format(I18nUtils.GetString("UIStrings", "CopiedTranslationResourceNum, resource.Key));
                    numCopied++;
                } catch { // errors thrown when a translation exists
                    lstSuccess.Items.Add(string.Format(I18nUtils.GetString("UIStrings", "TranslationExistsSkippingNum, resource.Key));
                }
            } else if(radIfExists.SelectedValue == "overwrite") {

                try {
                    cmd.ExecuteNonQuery();
                    lstSuccess.Items.Add(string.Format(I18nUtils.GetString("UIStrings", "OverwritingTranslationResourceNum, resource.Key));
                    numCopied++;
                } catch(Exception ex) { // any errors are SQL errors
                    lstErrors.Items.Add(string.Format(I18nUtils.GetString("Errors", "ErrorAddTranslationResourceNum, resource.Key, ex.Message));
                }

            }*/
            
            if(lstSuccess.Items.Count > 0) {
                pnlSuccess.Visible = true;
                plcSuccess.Controls.Add(lstSuccess);
                plcSuccess.Controls.Add(new LiteralControl("<p>" + I18nUtils.GetString("UIStrings", "TranslationCopyCompleteSummary", numCopied.ToString(), lstBaseLanguage.SelectedItem.Text, lstDestinationLanguage.SelectedItem.Text) + "</p>"));
            }
            if(lstErrors.Items.Count > 0) {
                pnlError.Visible = true;
                plcErrors.Controls.Add(lstErrors);
            }
            mltMain.ActiveViewIndex = 2;
        } catch(Exception ex) {
            lstErrors.Items.Add(I18nUtils.GetString("Errors", "Error") + ": " + ex.Message);
        }
    }
}
